<script setup lang="ts">
import {Back} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {reactive, ref} from "vue";
import type {SampleInfo} from '@/types'
import api from '@/api/index'
import {ElMessage} from "element-plus";
import type {FormRules} from "element-plus";
import {generateKey} from '@/utils/crypto'

const router = useRouter();

const addColumn = () => {
  sampleInfo.sampleData.push({key: '', value: '', type: 'string'})
}
const deleteColumn = () => {
  sampleInfo.sampleData.length > 1 ? sampleInfo.sampleData.pop() : ElMessage.error('至少保留一条数据')
}

let sampleInfo = reactive({
  collectionName: "collect_",
  namespace: "namespace_1",
  sampleId: generateKey(32),
  sampleData: [{key: '', value: '', type: 'string'}]
})

const options = ['string', 'number', 'boolean']

const addSample = () => {

  let a = true
  Object.keys(sampleInfo).forEach((item) => {
    if (item === 'sampleData') {
      for (let i = 0; i < sampleInfo[item].length; i++) {
        let note = 'sampleData[' + i + ']'
        if (sampleInfo[item][i].value.trim() === '' || sampleInfo[item][i].value === null) {
          ElMessage.error(note + '.value 请输入正确的' + sampleInfo[item][i].type + '类型数据')
          a = false
        } else {
          if (sampleInfo[item][i].type === 'number') {
            let b = Number(sampleInfo[item][i].value.trim())
            if (isNaN(b)) {
              ElMessage.error(note + '.value 请输入正确的number类型数据')
              a = false
            }
          } else if (sampleInfo[item][i].type === 'boolean') {
            if (sampleInfo[item][i].value.trim() !== 'true' || sampleInfo[item][i].value.trim() !== 'false') {
              ElMessage.error(note + '.value 请输入正确的boolean类型数据')
              a = false
            }
            a = false
          }
        }
        if (sampleInfo[item][i].key.trim() === '' || sampleInfo[item][i].key === null) {
          ElMessage.error('请完成表单信息！请输入' + item + '[' + i + '].key')
          a = false
        }
      }
    } else if (sampleInfo[item] === '' || sampleInfo[item] === null) {
      ElMessage.error('请完成表单信息！请输入' + item)
      a = false
    }
  })
  if (a) {
    api.addSample(sampleInfo).then(() => {
      ElMessage.success('添加成功')
      router.push('/sample')
    }).catch((err) => {
      ElMessage.error(err)
    })
  }


}
const regs = {
  // 小写字母、数字和下划线
  name: /^[a-z0-9_]+$/,
  id: /^[a-zA-Z0-9]+$/,
  email: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
  number: /^([0]|[1-9][0-9]*)$/,
  password: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*_]{8,}$/,
  shareCode: /^[A-Za-z0-9]+$/
}


const verify = (rule: any, value: any, callback: any) => {
  for (let i = 0; i < value.length; i++) {
    let data = value[i]
    let note = 'sampleData[' + i + ']'
    if (data.key.trim().length < 1 || data.key.trim().length > 32 || !regs.name.test(data.key)) {
      callback(new Error(note + '.key 请输入1-32位的字母、数字和下划线'))
      return
    }
    if (data.value.trim().length < 1) {
      callback(new Error(note + '.value 请输入正确的' + data.type + '类型数据'))
      return
    }
    if (data.type === 'number') {
      let a = Number(data.value.trim())
      if (isNaN(a)) {
        callback(new Error(note + '.value 请输入正确的Number类型数据'))
        return
      }

    } else if (data.type === 'boolean') {
      if (data.value.trim() != 'true' || data.value.trim() != 'false') {
        callback(new Error(note + '.value 请输入正确的Boolean类型数据'))
        return
      }

    } else {
      if (data.value.trim().length < 1 || data.value.trim().length > 512) {
        callback(new Error(note + '.value 请输入1-512位的字符'))
        return
      }
    }
  }
}


const ruleFormRef = ref()
const rules = reactive({
  namespace: [
    {required: true, message: '请输入命名空间', trigger: 'blur'},
    {min: 1, max: 12, message: '长度在 1到 12 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  collectionName: [
    {required: true, message: '请输入集合名称', trigger: 'blur'},
    {min: 1, max: 24, message: '长度在 1到 24 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  sampleData: [
    {required: true, message: '请输入样本属性字段', trigger: 'blur'},
    {validator: verify}
  ],
  sampleId: [
    {required: true, message: '请输入样本ID', trigger: 'blur'},
    {min: 1, max: 32, message: '长度在 1到 32 个字符', trigger: 'blur'},
    {pattern: regs.id, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
})


</script>
<template>
  <el-button type="primary" :icon="Back" @click="router.back()">返回</el-button>
  <el-form :model="sampleInfo" label-width="auto" :rules="rules" ref="ruleFormRef" style="max-width: 100%">
    <el-form-item label="namespace（命名空间）：" prop="namespace">
      <el-input v-model="sampleInfo.namespace" />
    </el-form-item>
    <el-form-item label="collectionName（集合名称）：" prop="collectionName">
      <el-input v-model="sampleInfo.collectionName"/>
    </el-form-item>
    <el-form-item label="sampleId（样本Id）：" prop="sampleId">
      <el-input v-model="sampleInfo.sampleId"/>
    </el-form-item>
    <el-form-item label="sampleData（自定义的样本属性字段）：" prop="sampleData">
      <div v-for="(item,index) in sampleInfo.sampleData" :key="index" class="flex gap-4 mb-4">

        KEY:&nbsp;<el-input v-model="item.key" placeholder="请输入字段名称" style="width: 200px"/>&nbsp;

        VALUE:&nbsp;<el-input v-model="item.value" placeholder="请输入字段值" style="width: 200px"/>&nbsp;
        dataType:&nbsp;
        <el-select v-model="item.type" placeholder="Select" style="width: 150px">
          <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </div>
      &nbsp;
      <div>
        <el-button type="primary" @click="addColumn">添加</el-button>
        <el-button type="primary" @click="deleteColumn">删除</el-button>
      </div>
    </el-form-item>
    <el-button type="primary" @click="addSample" style="width: 50%;font-size: 20px;margin-left: 25%">
      创建
    </el-button>
  </el-form>

</template>

<style scoped>

</style>